/**
 * Created by zzy on 2017/1/13.
 */
var $ = require('jquery');
var $alert = require('libs/alert');
var $form = require('js-path/formValide.js');
var $form2 = require('js-path/formValideNotSub.js');
var wms = false;
var wmsId = 4;
var owmsId = 5;
var owms = false;
$(function(){
    mainFormValidInit();
    $("#main_form input[name=systemId]").on("change",function () {
        if($(this).val()==wmsId){
            wms = true;
        }else if($(this).val() == owmsId){
            owms = true;
        }else {
            wms = false;
            owms = false;
        }

        if(wms){
            warehouseInit("DOME");
            $("#select_warehouse").attr("name","warehouseId");
            $("#div_warehouse").show();
        }else if(owms){
            warehouseInit("DEST");
            $("#select_warehouse").attr("name","warehouseId");
            $("#div_warehouse").show();
        }else{
            $("#select_warehouse").attr("name","");
            $("#div_warehouse").hide();
        }
    })
});
function warehouseInit(par) {
    $.ajax({
        url:'api/v1/p/crm/warehouse/query',
        type:'post',
        data:{
            warehouseType: par
        },
        dataType:"json",
        success:function (result) {
            $("#select_warehouse").html("<option value=''>全部</option>");
            $.each(result.data,function (index,obj) {
                $("#select_warehouse").append("<option value='"+obj.warehouseId+"'>"+obj.warehouseName+"</option>")
            })
        }
    })
}
function customValid() {
    var twicePwdFlag = true;
    var password1=$("#password").val();
    var password2=$("#password2").val();
    if(password1!=password2){
        $("#password2").parent().parent().addClass("has-error");
        $("#password2").parent().next("div").html('<p id="password2-error" class="error">两次密码输入不同</p>');
        twicePwdFlag = false;
    }
    return twicePwdFlag;
}
function mainFormValidInit(){
    $form({selector:'#main_form'},{
        username:{required:true},name:{required:true},password:{required:true},
        password2:{required:true},systemId:{required:true},warehouseId:{required:true}
    },{username:{required:'用户名不能为空'},name:{required:'用户姓名不能为空'},
        password:{required:'密码不能为空'},password2:{required:'重复密码不能为空'},systemId:{required:'所属系统不能为空'},
        warehouseId:{required:'所属仓库不能为空'}
    },function () {
        if(!customValid()){
            return false;
        }
        var json = $('#main_form').serializeObject();
        console.log(JSON.stringify(json))
        delete json.password2;
        return json;
    },function (result) {
        if(result.code == 200){
            window.location.href="user-manage";
        }else{
            $alert(result.message);
        }
    })
}